import { uploadImag, createRobotAccount, bindRobotAccount } from "../../api/webApi/index.js"
import { closeUnwantedPages } from "../../utils/index.js"
export async function fb_bindAccount_main(task, browser, index, taskId, bindAccountParams) {
  console.log("task====>", task)
  console.log("开始执行FaceBook绑定业务账号")
  try {
    let accountInfo = {
      account: "",
      nickName: "",
      avatar: "",
    }
    await new Promise((resolve) => setTimeout(() => resolve(), 1000 * 10))
    await closeUnwantedPages(browser, ["www.facebook.com"])
    const page = await browser.newPage()
    await page.setViewport({ width: 1920, height: 1080 })
    await new Promise((resolve) => setTimeout(() => resolve(), 1000 * 5))
    // 导航到Facebook网站
    await page.goto("https://www.facebook.com", {
      waitUntil: "networkidle2",
    })
    // 获取主页按钮
    const profileButtonSelector = ".x78zum5 > .x1i10hfl > .x1rg5ohu image"
    await page.waitForSelector(profileButtonSelector, { timeout: 10000 })
    const profileButton = await page.$(profileButtonSelector)
    console.log("个人主页按钮=====>", profileButton)

    // 等待昵称头像出现
    const nickNameSelector = "ul:nth-child(1) > li:nth-child(1) > div > .x1i10hfl > .x6s0dn4"
    await page.waitForSelector(nickNameSelector, { timeout: 10000 })

    // 获取输入框的位置信息
    const nickNameBox = await page.$(nickNameSelector)
    const nickNameBoxPosition = await nickNameBox.boundingBox()

    if (nickNameBoxPosition) {
      console.log("搜索完成！,等待页面接口响应")
      // 获取控件
      const userNickNameElement = await nickNameBox.$("#«R1d9laikqammjabiqapapd5aq» > .x1lliihq")
      // 获取里面昵称文本
      const userText = await page.evaluate((el) => el.textContent.trim(), userNickNameElement)
      console.log(`当前用户昵称: ${userText}`)
      accountInfo.nickName = userText
      // 获取用户账号
      const userAccount = accountInfo.nickName
      console.log(`当前用户账号: ${userAccount}`)
      accountInfo.account = userAccount
      // 获取头像图片（需要根据实际页面元素调整选择器）
      const avatarElement = await nickNameBox.$("ul:nth-child(1) > li:nth-child(1) > div:nth-child(1) > .x1i10hfl:nth-child(1) image:nth-child(1)")
      let avatarBuffer = null
      if (avatarElement) {
        const avatarSrc = await avatarElement.evaluate((el) => {
          return el.getAttribute("xlink:href")
        })
        const response = await page.goto(avatarSrc)
        avatarBuffer = await response.buffer()
        accountInfo.avatar = avatarBuffer
      }
      const blob = new Blob([avatarBuffer], { type: "image/png" }, "avatar.png")

      const formData = new FormData()
      formData.append("file", blob, {
        filename: "image.png",
        contentType: "image/png",
      })

      const uploadRes = await uploadImag(formData, { headers: { "Content-Type": "multipart/form-data" } })
      console.log("上传头像返回结果：", uploadRes.data)
      accountInfo.avatar = uploadRes.data
      console.log("获取到的账号信息：", accountInfo)
      const robotAccountRes = await createRobotAccount(
        {
          platformAccount: accountInfo.account,
          nickName: accountInfo.nickName,
          avatarUrl: accountInfo.avatar,
        },
        {
          headers: {
            "X-Platform": task.platformName,
            "X-Device-Id": task.deviceId,
            "tenant-id": task.tenantId,
          },
        }
      )
      console.log("创建机器人账号返回结果：", robotAccountRes.data)
      // 绑定机器人账号
      const bindRes = await bindRobotAccount(
        {
          platformAccount: accountInfo.account,
          platformName: task.platformName,
        },
        {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "X-Platform": task.platformName,
            "X-Device-Id": task.deviceId,
            "tenant-id": task.tenantId,
          },
        }
      )
      console.log("绑定机器人账号返回结果：", bindRes.data)

      // 明确返回成功结果
      return {
        success: true,
        account: accountInfo.account,
        message: `账号 ${accountInfo.account} 绑定成功`,
      }
    } else {
      throw new Error("无法获取用户信息区域")
    }
  } catch (error) {
    console.error("Facebook绑定账号过程出错：", error)
    // 明确抛出错误，以便上层Promise可以捕获
    throw error
  }
}

